﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace StuMana.UI
{
    public partial class StudentInfo : Office2007Form
    {
           // export excel
        Services.ExcelInterface excel = null;

        // datagridview variables
        public static Services.ConnectionController retrieveData = new Services.ConnectionController();

        // dataviewservice instance
        private Services.DataviewService dataview;// = new Services.DataviewService();

        private string query;
        string[] columnName = new string[7];
        string[] columnNameReal = new string[7];
        int time1;
        int time2;
        int page=0;
        int maxpage;
        static int rowperpage=1000;
        List<string>[] list;

        //textbox tagID variables
        private int action = 0;

       Label pages = new Label();
                
        // initial values
        public void studentInfo_initial()
        {
            pages.Text = "1";

            datagrid_config();
            dataview.setData(rowperpage, columnName, columnNameReal);
          //  dataview.DataOnDataGridViewInitial(dgvExDanhSach, query, time1, time2, pages);
        }
 
        // Forming the query from checkboxes
        private void datagrid_config(string tagID=null, string cbb_class=null, string name=null)
        {
            int i=1;
            Array.Resize<string>(ref columnName, 7);
            Array.Resize<string>(ref columnNameReal, 7);
            Array.Clear(columnName, 0, columnName.Length);
            Array.Clear(columnNameReal, 0, columnNameReal.Length);
            columnName[0] = "TagID";
            columnNameReal[0] = "TagID";
            query = "SELECT studentinfo.TagID,";
            time1 = -1;
            time2 = -1;
            if (cbXName.Checked){
                query += "studentinfo.Name,";
                columnName[i] = "Name";
                columnNameReal[i] = "Name";
                i++;
            }
            if (cbXBirthday.Checked){
                query += "studentinfo.BirthDay,";
                columnName[i] = "BirthDay";
                columnNameReal[i] = "BirthDay";  
                time1 = i;
                i++;
            }
            if (cbXGender.Checked){
                query += "studentinfo.Gender,";
                columnName[i] = "Gender";
                columnNameReal[i] = "Gender";
                i++;
            }
            if (cbXClass.Checked){
                query += "studentinfo.Class,";
                columnName[i] = "Class";
                columnNameReal[i] = "Class";
                i++;
            }
            if (cbXAccount.Checked){
                query += "studentinfo.Account,";
                columnName[i] = "Account";
                columnNameReal[i] = "Account";
              //  time2 = i;
                i++;
            }       

            if (cbXInOut.Checked){
                query += "studentInfo.inout_status,";
                columnName[i] = "inout_status";
                columnNameReal[i] = "inout_status";
                i++;
            }

            query = query.Remove(query.Length - 1, 1);
            query += " FROM studentinfo Where 1 ";
         
            if (cmbClass.Text != "All Class")
            {
                query += " and studentinfo.Class = N'" + cmbClass.Text + "'";
            }

            if (tagID != "" && tagID != null)
            {
                query +=" and studentinfo.TagID LIKE '"+tagID+"%'";
            }
            if (txtName.Text != "" && txtName.Text != null)
            {
                query += " and studentinfo.Name LIKE N'%" + txtName.Text + "%'";
            }
            Array.Resize<string>(ref columnName, i);
            Array.Resize<string>(ref columnNameReal, i);
        }

        // tb1 keydown to decide whether acting
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyValue >= 48 && e.KeyValue <= 57)||(e.KeyValue >= 96 && e.KeyValue <= 105))
            {
                action = 1;
                labelItemStatus.Text = "None";
            }
            else if (e.KeyValue == 46)
            {
                action = 1;
            }
            else if (e.KeyValue != 8)
            {
                action = 2;
                labelItemStatus.Text = "Number only";
            }
        }

        // tagID textbox type
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            switch (action)
            {
                //remove last input character
                case 2:
                    remove_character();
                    break;
                default:                    
                    break;
            }
        }

        // remove the last character input
        private void remove_character()
        {
            int temp = txtTagID.SelectionStart;
            if (temp > 0)
            {
                txtTagID.Text = txtTagID.Text.Remove(temp - 1, 1);
                txtTagID.SelectionStart = temp - 1;
            }
        }

        //set status to ts_connect
        public void setStatus(string stt)
        {
            labelItemConnect.Text = stt;
        }

        private bool flag = false;
        private bool co = false;
        private System.Drawing.Font fontForAll = null;
        private StyleManager managerStyle = new DevComponents.DotNetBar.StyleManager();

        public void ReadSetting()
        {
            XmlReader reader = XmlReader.Create("Settings.xml");
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element
                && reader.Name == "font")
                {
                    string name = reader.GetAttribute(0).ToString();
                    string style = reader.GetAttribute(1).ToString();
                    float size = float.Parse(reader.GetAttribute(2).ToString());
                    if (style == "Bold")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Italic")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Regular")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Strikeout")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Strikeout, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Underline")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.Name == "managerstyle" && reader.NodeType == XmlNodeType.Element)
                        {
                            reader.Read();
                            string stylemana = reader.Value.ToString();

                            if (stylemana == "Office2007Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Blue;
                            if (stylemana == "Office2007Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Silver;
                            if (stylemana == "Office2007Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Black;
                            if (stylemana == "Windows7Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Windows7Blue;
                            if (stylemana == "Office2007VistaGlass")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007VistaGlass;
                            if (stylemana == "Office2010Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Silver;
                            if (stylemana == "Office2010Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Blue;
                            if (stylemana == "Office2010Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Black;
                        }
                    }
                }
            }
            reader.Close();
        }

        public void ConfigSetting()
        {
            ReadSetting();
            for (int i = 0; i < Controls[0].Controls[1].Controls[2].Controls.Count; i++)
            {
                if (Controls[0].Controls[1].Controls[2].Controls[i] is LabelX)
                {
                    Controls[0].Controls[1].Controls[2].Controls[i].Font = fontForAll;
                }
            }

            for (int i = 0; i < Controls[0].Controls[1].Controls[4].Controls.Count; i++)
            {
                if (Controls[0].Controls[1].Controls[4].Controls[i] is LabelX)
                {
                    Controls[0].Controls[1].Controls[4].Controls[i].Font = fontForAll;
                }
            }
            styleManager1 = managerStyle;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        { 
            pages.Text = "1";
            //bt_next.Enabled = true;
            datagrid_config(txtTagID.Text);
            dataview.setData(rowperpage, columnName, columnNameReal);
            dataview.DataOnDataGridViewInitial(dgvExDanhSach, query, time1,time2,pages);

            // thay doi kich thuoc cot sau khi tim kiem 
            if (dgvExDanhSach.Columns.Count > 0)
            {
                int w = dgvExDanhSach.Size.Width;
                int widthC = ((int)w / dgvExDanhSach.Columns.Count);
                if (co == true)
                {
                    for (int i = 0; i < dgvExDanhSach.Columns.Count; i++)
                    {
                        dgvExDanhSach.Columns[i].Width = widthC;
                    }
                }

            }
            if (dgvExDanhSach.Rows.Count == 0)
            {
                MessageBoxEx.Show("List Student is empty ", "Information ", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnXExcel_Click(object sender, EventArgs e)
        {
            list = dataview.GetList();
            excel = new Services.ExcelInterface(list,columnName,time1,2,time2,1);
        }

        private void btnXPdf_Click(object sender, EventArgs e)
        {
            if (dgvExDanhSach.Rows.Count > 0)
            {
                SaveFileDialog sfdlog = new SaveFileDialog();
                sfdlog.Filter = "PDF files (*.pdf)|*.pdf|All file (*.*)|*.*";
                sfdlog.FilterIndex = 1;
                DialogResult dlog = sfdlog.ShowDialog();
                if (dlog == DialogResult.OK)
                {
                    string name = sfdlog.FileName.ToString();
                    ExportPDF(dgvExDanhSach, name);
                }
            }
            else
            {
                MessageBox.Show(" Data is empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        public void ExportPDF(DevComponents.DotNetBar.Controls.DataGridViewX dgv,string path)
        {
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
            document.Open();
            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);

            //Full path to the Unicode Arial file
            string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");

            //Create a base font object making sure to specify IDENTITY-H
            BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            //Create a specific font object
            iTextSharp.text.Font f = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL);

            PdfPTable table = new PdfPTable(dgv.Columns.Count);
            PdfPRow row = null;

            float[] widths = new float[dgv.Columns.Count];
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                widths[i] = 4f;
            }
        
            table.SetWidths(widths);

            table.WidthPercentage = 100;
            int iCol = 0;
            string colname = "";
            PdfPCell cell = new PdfPCell(new Phrase("Products"));

            cell.Colspan = dgv.Columns.Count;

            foreach (DataGridViewColumn c in dgv.Columns)
            {
                table.AddCell(new Phrase(c.HeaderCell.Value.ToString(), f));
            }

            foreach (DataGridViewRow r in dgv.Rows)
            {
                if (dgv.Rows.Count > 0)
                {
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        table.AddCell(new Phrase(r.Cells[i].Value.ToString(), f));
                    }
                }
            } 
            document.Add(table);
            document.Close();
        }
       
        public StudentInfo()
        {
            InitializeComponent();
            dataview = new Services.DataviewService();
          //  studentInfo_initial();
        }

        private void StudentInfo_Load(object sender, EventArgs e)
        {
            flag = true;

            cmbClass.Items.Add("All Class");
            cmbClass.Items.Add("10A1");
            cmbClass.Items.Add("10A2");
            cmbClass.Items.Add("10A3");
            cmbClass.Items.Add("10A4");
            cmbClass.Items.Add("10A5");
            cmbClass.Items.Add("10A6");
            cmbClass.Items.Add("10A7");
            cmbClass.Items.Add("10A8");
            cmbClass.Items.Add("10A9");

            cmbClass.Items.Add("11A1");
            cmbClass.Items.Add("11A2");
            cmbClass.Items.Add("11A3");
            cmbClass.Items.Add("11A4");
            cmbClass.Items.Add("11A5");
            cmbClass.Items.Add("11A6");
            cmbClass.Items.Add("11A7");
            cmbClass.Items.Add("11A8");
            cmbClass.Items.Add("11A9");

            cmbClass.Items.Add("12A1");
            cmbClass.Items.Add("12A2");
            cmbClass.Items.Add("12A3");
            cmbClass.Items.Add("12A4");
            cmbClass.Items.Add("12A5");
            cmbClass.Items.Add("12A6");
            cmbClass.Items.Add("12A7");
            cmbClass.Items.Add("12A8");
            cmbClass.Items.Add("12A9");

            cmbClass.SelectedIndex = 0;
            ConfigSetting();
            co = true;
        }

        private void StudentInfo_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
        }

        private void StudentInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
        }

        private void StudentInfo_Resize(object sender, EventArgs e)
        {
            if (dgvExDanhSach.Columns.Count > 0)
            {
                int w = dgvExDanhSach.Size.Width;
                int widthC = ((int)w / dgvExDanhSach.Columns.Count);
                if (co == true)
                {
                    for (int i = 0; i < dgvExDanhSach.Columns.Count; i++)
                    {
                        dgvExDanhSach.Columns[i].Width = widthC;
                    }
                }
            }
        }
    }
}
